<?php

/**
 * Generator class
 *
 * @author Eugene I. Nezhuta
 */
class RCMS_Object_Generator_Generator {

	const PLUGIN_ENABLED  = 'enabled';

	const PLUGIN_DISABLED = 'disabled';

/**
 * Generator view path
 *
 */
	const VIEW_PATH = '/views/scripts/generator';

	/**
	 * Seo varriable top. (Used to integrate code from Google for analitics, wmtools)
	 *
	 */
	const SEOVAR_TOP = 'top';

	/**
	 * Seo varriable bottom. (Used to integrate code from Google for analitics, wmtools)
	 *
	 */
	const SEOVAR_BOTTOM = 'bottom';


	/**
	 * Generator model
	 *
	 * @var RCMS_Object_Generator_GeneratorModel
	 */
	private $_model = null;

	/**
	 * Allows generator add linkks (Add/Edit) to generated content
	 *
	 * @var boolean
	 */
	private $_addLinks = true;

	/**
	 * Website path
	 *
	 * @var string
	 */
	private $_sitePath = '';

	/**
	 * Website url
	 *
	 * @var string
	 */
	private $_siteUrl = '';

	/**
	 * Generator view
	 *
	 * @var Zend_View
	 */
	private $_generatorView = null;

	/**
	 * Language Id (english, spanish, etc...)
	 *
	 * @var string
	 */
	private $_languageId = '';

	private $_memberLogged = false;

	/**
	 * Constructor
	 *
	 * @param boolean $addLinks
	 */
	public function  __construct($addLinks = true, $pluginConfigData = null, $languageId = '', $memberLogged = false) {
		$this->_languageId = ($languageId != '') ? $languageId : '';
		$this->_model = new RCMS_Object_Generator_GeneratorModel();
		$this->_addLinks = $addLinks;
		$this->_memberLogged = $memberLogged;
		$this->_sitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
		$this->_siteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$this->_generatorView = new Zend_View();
		//$this->_generatorView->setScriptPath($this->_sitePath . self::VIEW_PATH);
        $this->_generatorView->setScriptPath(APPLICATION_PATH . self::VIEW_PATH);
		$this->_generatorView->websiteUrl = $this->_siteUrl;
	}

	/**
	 * Generate website main navigation menu
	 *
	 * @return string
	 */
	public function generateMainMenu($expanded = false, $pageData = array(), $takeDraft = true) {
		$categories = $this->_model->getMainMenuCategories($takeDraft);
		foreach($categories as $key => $category) {
			if($category['protected'] == '1') {
				if(!$this->_addLinks && !$this->_memberLogged) {
					unset($categories[$key]);
					continue;
				}
			}
			$pages = $this->_model->getMainMenuCategoryPages($category['categoryId']);
//			$pages = $categories[$key]['pages'];
			foreach ($pages as $pkey => $page) {
				if($page['protected'] == '1') {
					if(!$this->_addLinks && !$this->_memberLogged) {
						unset($pages[$pkey]);
						continue;
					}
				}
//				$pages[$pkey]['url'] = urldecode($page['url']);
			}

			$categories[$key]['pages'] = $pages;
		}
		//var_dump($categories);die();
		$this->_generatorView->sitePages = $categories;
		$this->_generatorView->classCounter = 0;
		if($expanded) {
			foreach ($categories as $catPage) {
				$page = new RCMS_Object_Page_Page($pageData['id']);
				if($page->getIsCategory()) {
					$this->_generatorView->currCat = $page->getUrl();
				}
				else {
					$catPageId = $this->_model->getPageIdByCategoryId($page->getParentCategoryId());
					$catPage = new RCMS_Object_Page_Page($catPageId);
					$this->_generatorView->currCat = $catPage->getUrl();
				}

			}
			return $this->_generatorView->render('mainmenuext.phtml');
		}
		return $this->_generatorView->render('mainmenu.phtml');
	}


	/**
	 * Generate site secondary "static" menu
	 *
	 * @return string
	 */
	public function generateStaticMenu() {
		$staticMenuPages = $this->_model->getStaicMenuPages();
		foreach ($staticMenuPages as $key => $page) {
			if($page['protected'] == '1') {
				if(!$this->_addLinks && !$this->_memberLogged) {
					unset($staticMenuPages[$key]);
					continue;
				}
			}
		}
		$this->_generatorView->staticPages = $staticMenuPages;
		return $this->_generatorView->render('staticmenu.phtml');
	}

	/**
	 * Generate right content for '{$content}' containers
	 *
	 * @param string $containerName
	 * @param array $oageData
	 * @return string
	 */
	public function generateContentContainer($containerName, $pageData) {
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id']);
		$replacedContent = $data['value'] . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_CONTENT, $containerName, $data['id_container'], $pageData['id'], ($data === null || !$data));
		if($data['published'] === '0') {
            if ($this->_addLinks) {
                $replacedContent = $this->_wrapUnPublished($replacedContent);
            } else {
                $replacedContent = '';
            }
		}
		return $replacedContent;
	}

	/**
	 * Generates content for static containers
	 *
	 * @param string $containerName
	 * @return string
	 */
	public function generateStaticContent($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName);
		return $data['value'] . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_STATIC, $containerName, $data['id_container'], null, ($data === null || !$data));
	}

	public function generateStaticHeaderContent($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName, RCMS_Object_Container_Container::C_TYPE_STATICHEADER);
		return $data['value'] . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_STATICHEADER, $containerName, $data['id_container'], null, ($data === null || !$data));
	}

	public function generateGoogleMap($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName, RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP);
		return $data['value'] . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP, $containerName, $data['id_container'], null, ($data === null || !$data));
	}

	/**
	 * Generate content for header container
	 *
	 * @param string $containerName
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateHeaderContent($containerName, $pageData) {
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id'], RCMS_Object_Container_Container::C_TYPE_HEADER);
		return $data['value'] . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_HEADER, $containerName, $data['id_container'], $pageData['id'], ($data === null || !$data));
	}

	public function generateCodeContent($containerName, $pageData) {
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id'], RCMS_Object_Container_Container::C_TYPE_CODE);
        if ($data){
            if(!preg_match('/^<script>.*/', $data['value'])) {
                $data['value'] = eval($data['value']);
            }
        }
		return ($data ? $data['value']:'') . $this->_addLinks(RCMS_Object_Container_Container::C_TYPE_CODE, $containerName, isset($data['id_container']) ? $data['id_container'] : '', $pageData['id'], !$data);
	}

	/**
	 * Generate content for featured area
	 *
	 * @param string $name
	 * @param array $options container options
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateFeaturedAreaContent($name, $options, $pageData) {
		$page = new RCMS_Object_Page_Page($pageData['id']);
		$featuredArea = new RCMS_Object_FeaturedArea_FeaturedArea();
		$featuredArea = $featuredArea->_model->selectFeaturedAreaByName($name);
		if($featuredArea) {
			if(empty($options))
				$options[0] = 0;
			if($featuredArea->id > 0) {
				$pages = $this->_model->getPagesListByFeaturedId($featuredArea->id, $page->getId(), $options[0]);
			}
			$this->_generatorView->featuredAreaName = str_replace(" ", "-",strtolower($name));
            $this->_generatorView->faId = $featuredArea->id;
			if(isset($options[1])) {
				foreach ($pages as $key => &$page) {
					$page['description'] = $this->cutDescription($page['description'],$options[1]);
                    $p = new RCMS_Object_Page_Page($page['page_id']);
                    $catName = $p->getParentCategoryName();
                    $catName = isset($catName['name']) ? trim($catName['name']) : '';
                    if ($p->getIs404Page() == 1 || preg_match('/draft pages/i', $catName)) {
                        unset ($pages[$key]);
                    }
                    unset ($p);
				}
			}
            
			$random = (isset($options[2]) && $options[2]== 'random');
			$pages = $this->_proccessFaPages($pages, $options[0], $random);
			
			$this->_generatorView->featuredPagesList = $pages;
			$this->_generatorView->isLogged = $this->_addLinks;
			if(!empty ($pages)) {
				$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
				return $translator->processScreen($this->_generatorView->render('featuredareapagelist.phtml'));
			}
		}
		else {
			return '';
		}
	}

	/**
	 * Method used to limit and randomize pages in Featured area
	 * @param array $pages 
	 * @param array $limit
	 * @return array proccessed list of pages 
	 */
	private function _proccessFaPages($pages, $limit, $randomize = false) {
		$countPages = sizeof($pages);
		$limit = is_numeric($limit) ? intval($limit) : 0;
		if ($countPages) {
			if ($randomize) {
				shuffle($pages);
			}
			if ( 0 < $limit && $limit < $countPages) {
				$pages = array_slice($pages, 0, $limit);
			}
		}
		return $pages;
	}

	/**
	 * Generate content for featured area with images
	 *
	 * @param string $name
	 * @param array $options container options
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateFeaturedAreaImgContent($name, $options, $pageData) {
		$addLink = "";
		if($this->_addLinks) {
			$addLink = '<a title="Order Pages" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_featuredarea/orderfa/name/'.$name.'/?TB_iframe=true&height=600&width=600\',\' \')" class="generator-links">Order Pages</a>';
		}

		$page = new RCMS_Object_Page_Page($pageData['id']);
		$featuredArea = new RCMS_Object_FeaturedArea_FeaturedArea();
		$featuredArea = $featuredArea->_model->selectFeaturedAreaByName($name);
		if($featuredArea) {
			if(empty($options)) {
				$options[0] = 0;
			}
			if($featuredArea->id>0)
			$pages = $this->_model->getPagesListImagesByFeaturedId($featuredArea->id,$page->getId(),$options[0]);
			$this->_generatorView->featuredAreaName = str_replace(" ", "-",strtolower($name));
			$this->_generatorView->faId = $featuredArea->id;
			if(isset($options[1])) {
				foreach ($pages as $key => &$page) {
					$page['description'] = $this->cutDescription($page['description'],$options[1]);
                    $p = new RCMS_Object_Page_Page($page['page_id']);
                    $catName = $p->getParentCategoryName();
                    $catName = isset($catName['name']) ? trim($catName['name']) : '';
                    if ($p->getIs404Page() == 1 || preg_match('/draft pages/i', $catName)) {
                        unset ($pages[$key]);
                    }
                    unset ($p);
				}

			}
			
			$random = (isset($options[2]) && $options[2]== 'random');
			$pages = $this->_proccessFaPages($pages, $options[0], $random);
			
			$this->_generatorView->isLogged = $this->_addLinks;
			$this->_generatorView->featuredPagesList = $pages;

			//take image dimensions from config
			//$configData                                = $this->_model->selectConfig();
			//$this->_generatorView->pageTeaserImageSize = $configData['page_teaser_size'];

			if(!empty ($pages)) {
				$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
				return $translator->processScreen($this->_generatorView->render('featuredareapageimgagelist.phtml'));
			}
			return '';
		}
		return '';

	}

	/**
	 * Generate list of pages for specified category
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generatePagesList($pageData) {

		$page = new RCMS_Object_Page_Page($pageData['id']);
		$catId = ($page->getParentCategoryId() == 0) ? $page->getCategoryId() : $page->getParentCategoryId();
		$pages = $this->_model->getCategoryPagesList($catId);
		$this->_generatorView->categoryPagesList = $pages;
		return $this->_generatorView->render('catpageslist.phtml');
	}

	/**
	 * Generate categories list with images or not if scecified
	 *
	 * @param boolean $withImages
	 * @return string
	 */
	public function generateCategoriesList($withImages = false, $takeDraft = true) {
		$categories = $this->_model->getCategoriesList($takeDraft);
		$this->_generatorView->categoriesList = $categories;
		if($withImages) {
			return $this->_generatorView->render('catlistimg.phtml');
		}
		return $this->_generatorView->render('catlist.phtml');
	}

	/**
	 * Generate list of pages for specified category.
	 *
	 * Shows only pages images with page's short description
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generatePagesListImg($pageData) {
		$page = new RCMS_Object_Page_Page($pageData['id']);
		$catId = ($page->getParentCategoryId() == 0) ? $page->getCategoryId() : $page->getParentCategoryId();
		$pages = $this->_model->getCategoryPagesListImg($catId);
		$this->_generatorView->categoryPagesListImg = $pages;
		return $this->_generatorView->render('catpageslistimg.phtml');
	}


	/**
	 * Generate site map
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generateSiteMap($pageData) {
		$categories = $this->_model->getSiteMapCategories();
		$page404Id = $this->_model->get404PageId();
		foreach($categories as $key => $category) {
			$categories[$key]['pages'] = $this->_model->getSiteMapCategoryPages($category['categoryId']);
		}
		$this->_generatorView->siteMapPages = $categories;
		$newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->newsFolder = ($newsFolder) ? $newsFolder : 'news';
		return $this->_generatorView->render('sitemap.phtml');
	}

	/**
	 * Generate xml sitemap
	 *
	 * @param array $sitePages
	 */
	public function generateSiteMapXml($sitePages) {
		$this->_generatorView->pages = $sitePages;
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->newsFolder = ($newsFolder) ? $newsFolder : 'news';
		$this->_generatorView->lastMod = date('c', time());
		$fileContent = $this->_generatorView->render('sitemapxml.phtml');
		RCMS_Tools_FilesystemTools::saveFile('sitemap.xml', $fileContent);
	}

	/**
	 * Generates 301 redirect for renamed pages and put it into htaccess file
	 *
	 * @param array $redirectTable
	 */
	public function generateRedirects($redirectTable) {
		$additionalRulesContent = '';
		try {
			$additionalRulesContent = RCMS_Tools_FilesystemTools::getFile($this->_sitePath . '.xrules');
		}
		catch (Exception $e) {
			$additionalRulesContent = false;
		}
		$parsedUrl = parse_url($this->_siteUrl);
		$this->_generatorView->siteDir = trim($parsedUrl['path'], '/');
		$this->_generatorView->redirectTable = $redirectTable;
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->additionalRules = $additionalRulesContent;
		$htaccess = $this->_generatorView->render('htaccess.phtml');
		RCMS_Tools_FilesystemTools::saveFile($this->_sitePath . '.htaccess', $htaccess);
	}

	/**
	 * Generate category name for {$categoru_name} variable
	 *
	 * @param integer $pageId
	 * @return string
	 */
	public function generateCategoryName($pageId) {
		$page = new RCMS_Object_Page_Page($pageId, true);
		$result = $page->getParentCategoryName();
		return $result['name'];
	}


	/**
	 * Generate related page variable's content
	 *
	 * @param integer $countKeywords amount of keywords to be the same
	 * @param array $options container options
	 * @param array $data current page data
	 * @param boolean $withImg generate content with images or not
	 * @return string
	 */
	public function generateRelatedPages($countKeywords, $options, $data, $withImg = false) {
		if(intval($countKeywords) == 0 || !isset($options[0]) || intval($options[0]) == 0) {
			return '';
		}
		$relatedPagesIds = array();
		$currentPageKeywords = explode(",", $data['meta_keywords']);
		foreach ($currentPageKeywords as $key => $value) {
			$currentPageKeywords[$key] = trim($value);
		}
		if(count($currentPageKeywords) >= $countKeywords) {
			$limit = $options[0];
			$allKeyWordsAndIds = $this->_model->getAllPagesIdsAndKeywords($data['id']);
			foreach ($allKeyWordsAndIds as $idKeywords) {
				$idKeywords['keywords'] = explode(",", $idKeywords['keywords']);
				foreach ($idKeywords['keywords'] as $key => $value) {
					$idKeywords['keywords'][$key] = trim($value);
				}
				foreach ($currentPageKeywords as $keyword) {
					if(empty ($keyword)) {
						continue;
					}
					if(count(array_intersect($currentPageKeywords, $idKeywords['keywords'])) >= $countKeywords) {
                        $page = new RCMS_Object_Page_Page($idKeywords['id']);
                        $catName = $page->getParentCategoryName();
                        $catName = isset($catName['name']) ? trim($catName['name']) : '';
                        if (!$page->getIs404Page() && !preg_match('/draft pages/i', $catName)) {
                            $relatedPagesIds[] = $idKeywords['id'];
                        }
                        unset ($page);
					}
				}
			}
			$relatedPagesData = $this->_model->getRelatedPagesData($relatedPagesIds, $limit, $withImg);
			$this->_generatorView->relatedPagesData = $relatedPagesData;
		}
		else {
			$this->_generatorView->relatedPagesData = array();
		}
		$this->_generatorView->withImage = $withImg;
		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		$relateds	= $translator->processScreen($this->_generatorView->render('related.phtml'));
		return $relateds;
	}

	/**
	 * Generate comments block content
	 *
	 * @param string $containerName
	 * @param array $options
	 * @param array $pageData
	 * @param boolean $isLogged
	 * @return string
	 */
	public function generateComments($containerName, $options,$pageData,$isLogged) {
	//clearing page with captcha from the cache
		$captchaId = RCMS_Tools_Tools::generateCaptcha();
		$topic = (isset($options[0]))? $options[0] : "";
		$keyword = (isset($options[1]))? $options[1] : "";
		$countComments = (isset($options[2]))? $options[2] : 4;
		$publishedByDefault = (isset($options[3]))? $options[3] : 0;

		$containerData = $this->_model->selectContainerTextData($containerName, $pageData['id']);
		$commentsArray = $this->_model->selectCommenstByContainerId($containerData['id_container'],$isLogged);

		//October 8, 2009 at 2:41 pm
		foreach ($commentsArray as &$comment) {
			$comment['date'] = RCMS_Tools_Tools::proccessPublishingDateCommentsFromSql($comment['date']);
		}
		$this->_generatorView->requestedPage  = $pageData['url'].".html";
		$this->_generatorView->captchaId = $captchaId;
		$this->_generatorView->topic = $topic;
		$this->_generatorView->keyword = $keyword;
		$this->_generatorView->countComments = $countComments;
		$this->_generatorView->publishedByDefault = $publishedByDefault;

		$this->_generatorView->isLogged = $this->_addLinks;
		$this->_generatorView->commentsBlockName = str_replace(" ", "-",$containerName);
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->containerId = $containerData['id_container'];
		$this->_generatorView->commentsArray = $commentsArray;
		//return $this->_generatorView->render('comments.phtml');

		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		$comments = $translator->processScreen($this->_generatorView->render('comments.phtml'));
		return $comments;
	}



	/**
	 * Generate new item varriable
	 *
	 * @param string $newsTitle
	 * @param array $options
	 * @param array $newsData
	 * @return string
	 */
	public function generateNewsItem($newsTitle, $options, $newsData) {
		$date= '';
		$newsItemObj = '';
		if(!empty ($newsTitle)) {
			$newsItemObj = $this->_model->selectNewsByTitle(trim($newsTitle));
			if($newsItemObj) {
				$date = $this->processNewsDate($newsItemObj->newsDate);
			}
		}
		else //process varible newsitem
		{
			if($newsData['requestedNewsPage'] != 'index.html') {
				$requestedNewsPage = explode('.', trim($newsData['requestedNewsPage']));
				$newsItemObj = $this->_model->selectNewsByUrl($requestedNewsPage[0]);

				if(!$newsItemObj && isset($newsData['newsUrl'])) {
					$newsItemObj = $this->_model->selectNewsByUrl($newsData['newsUrl']);
				}
				if($newsItemObj) {
					$date = $this->processNewsDate($newsItemObj->newsDate);
				}
			}
		}
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsItemObj = $newsItemObj;
		$this->_generatorView->date = $date;
		return $this->_generatorView->render('newsitem.phtml');
	}

	public function generateNewsTitle($newsTitle, $options, $newsData) {
/*
		$date= '';
		$newsItemObj = '';
		if(!empty ($newsTitle)) {
			$newsItemObj = $this->_model->selectNewsByTitle(trim($newsTitle));
			if($newsItemObj) {
				$date = $this->processNewsDate($newsItemObj->newsLastUpdate);
			}
		}
		else //process varible newsitem
		{
			if($newsData['requestedNewsPage'] != 'index.html') {
				$requestedNewsPage = explode('.', trim($newsData['requestedNewsPage']));
				$newsItemObj = $this->_model->selectNewsByUrl($requestedNewsPage[0]);
				if($newsItemObj) {
					$date = $this->processNewsDate($newsItemObj->newsLastUpdate);
				}
			}
		}
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsItemObj = $newsItemObj;
		$this->_generatorView->date = $date;
		return $this->_generatorView->render('newsitem.phtml');*/
	}

	/**
	 * Generate news list varriable content for news template
	 *
	 * @return string
	 */
	public function generateNewsList() {
		$newsCategoriesArray = $this->_model->selectAllNewsCategories();
		$newsArray = $this->_model->selectAllNews();
		foreach ($newsArray as &$news) {
			$news['newsDate'] = $this->processNewsDate($news['newsDate']);
		}
		$newsArrayWithoutCategory = $this->_model->selectAllNews(0);
		foreach ($newsArrayWithoutCategory as &$news) {
			$news['newsDate'] = $this->processNewsDate($news['newsDate']);
		}
		$newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->newsFolder = ($newsFolder) ? $newsFolder : 'news';
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsCategoriesArray = $newsCategoriesArray;
		$this->_generatorView->newsArray = $newsArray;
		$this->_generatorView->newsArrayWithoutCategory = $newsArrayWithoutCategory;
		return $this->_generatorView->render('newslist.phtml');
	}

	/**
	 * Proccess and return valid news item's date
	 *
	 * @param string $newsDate
	 * @return string
	 */
	public function processNewsDate($newsDate) {
		$explodeFirst = explode(" ", $newsDate);
		$date = explode("-",$explodeFirst[0]);
		return date("F jS Y",mktime(0, 0, 0, $date[1], $date[2], $date[0]));
	}

	/**
	 * Generate image gallery content
	 *
	 * @param array $params
	 * @return string
	 */
	public function generateGallery($params) {
		$gallery = $params['name'];
		$config = unserialize(Zend_Registry::get('config'));
		$path = $config->website->website->path . $config->website->website->galleries;

		if($gallery != '' && is_dir($path . $gallery) &&
			is_dir($path . $gallery . '/thumbnails/') && file_exists($path . $gallery . '/settings.txt')) {
			$pathGallery = explode('/', $config->website->website->galleries);
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
			$this->_generatorView->settings = explode(':', @file_get_contents($path . $gallery . '/settings.txt'));
			$this->_generatorView->pathGallery = ($pathGallery[(count($pathGallery)-1)]!=''?$pathGallery[(count($pathGallery)-1)]:'galleries');
			$this->_generatorView->galleryName = $gallery;
			$this->_generatorView->siteUrl = $this->_siteUrl;
			$this->_generatorView->isLogin = $this->_addLinks;
			return $this->_generatorView->render('gallery.phtml');
		}

		if(preg_match("/^[a-z-]{1,225}$/", $gallery)) {
			if(!is_dir($path . $gallery)) {
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery);
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery .'/thumbnails/');
				if(!empty($params['options'])) {
					$settings = (isset($params['options'][0]) && intval($params['options'][0])>0?$params['options'][0]:'125') . ':';
					$settings .= (isset($params['options'][1]) && $params['options'][1]==1?'1':'0') . ':';
					$settings .= (isset($params['options'][2]) && $params['options'][2]==1?'1':'0') . ':';
					$settings .= (isset($params['options'][3]) && $params['options'][3]==1?'1':'0');
					@file_put_contents($path . $gallery .'/settings.txt', $settings);
				}
				else {
					@file_put_contents($path . $gallery .'/settings.txt', '125:1:1:1');
				}
				$pathGallery = explode('/', $config->website->website->galleries);
				$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
				$this->_generatorView->settings = explode(':', @file_get_contents($path . $gallery . '/settings.txt'));
				$this->_generatorView->pathGallery = ($pathGallery[(count($pathGallery)-1)]!=''?$pathGallery[(count($pathGallery)-1)]:'galleries');
				$this->_generatorView->galleryName = $gallery;
				$this->_generatorView->siteUrl = $this->_siteUrl;
				$this->_generatorView->isLogin = $this->_addLinks;
				return $this->_generatorView->render('gallery.phtml');
			}
		}
		return '';
	}

	/**
	 * Regenerate news routes xml file according to the news folder recived from seosamba
	 *
	 */
	public function generateNewsRoutes() {
		$newsFolder = $this->_model->getNewsFolder();
		$newsFolder = ($newsFolder) ? $newsFolder : 'news';
		$routesPath                     = APPLICATION_PATH . '/configs/' . SITE_NAME . 'routesext.xml';
		$routes                         = new Zend_Config_Xml($routesPath, 'routes', array('allowModifications' => true));
		$routes->newsroute->route       = '/' . $newsFolder . '/:news_url';
		$routes->newsindexroute->route  = '/' . $newsFolder . '/index.html';
		$routes->newsfolderroute->route = '/' . $newsFolder . '/';
		$writer                         = new Zend_Config_Writer_Xml();
		$writer->setConfig($routes);
		$writer->write($routesPath);
	}

	/**
	 * Generates paypal button form
	 *
	 * @param array $params
	 * @return string
	 */
	public function generateFormPayPal($params) {
		if(empty($params) || intval($params['name']) < 0 || count($params['options']) < 4) {
			return '' ;
		}

		$email = $this->_model->selectConfigGetEmailAdmin();
		$this->_generatorView->email = $email['admin_email']['value'];
		$this->_generatorView->price = $params['name'];
		$this->_generatorView->option1 = $params['options'][0];
		$this->_generatorView->value1 = $params['options'][1];
		$this->_generatorView->option2 = $params['options'][2];
		$this->_generatorView->value2 = $params['options'][3];
		return $this->_generatorView->render('paypalbutton.phtml');
	}

	/**
	 * Generates custom payment button content
	 *
	 * @param array $params
	 * @return string
	 */
	public function generatePaymentButton($params) {
		if(empty($params) || intval($params['name'])) {
			return '' ;
		}

		if(preg_match("/^[a-zA-Z0-9_-]{1,225}$/", $params['name'])) {
			$data = $this->_model->selectPaymentButtonByName($params['name']);
			if(is_array($data) && isset($data[0]['value']) && $data[0]['value'] != '') {
				return $data[0]['value'];
			} else {
				return '';
			}
		}
		return '';
	}

	/**
	 * Try to find content for unknown varriable
	 *
	 * @param string $variableName
	 * @return string
	 */
	public function generateUnknown($variableName) {
		return $this->_model->getVariableCode($variableName);
	}

	/**
	 * Generates news scroller content
	 *
	 * @return string
	 */
	public function generateNewsScroller() {
		$this->_generatorView->newsList = $this->_model->selectNewsItemsForScroller();
		$newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->newsFolder = ($newsFolder) ? $newsFolder : 'news';
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		return $this->_generatorView->render('newsscroller.phtml');
	}

	/**
	 * Generate a correct rss feed link
	 *
	 * @param array $containerParams
	 * @return string
	 */
	public function generateRssFeedLink($containerParams) {
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->rssFeedName = $containerParams['name'];
		return $this->_generatorView->render('rsslink.phtml');
	}

	/**
	 * Generates custom user form
	 *
	 * @param string $containerName
	 * @param array $options
	 * @param array $pageData
	 * @return string
	 */
	public function generateForm($containerName, $options, $pageData) {
		$captchaId = '';
		if(!empty($options)) {
			if(isset($options[0]) && $options[0]=='captcha') {
				$captchaId = RCMS_Tools_Tools::generateCaptcha();
			}
		}
		$formObj = null;
		$formId = $this->_model->getFormId($containerName);
		$replacedContent = '';
		if($formId) {
			$formObj = new RCMS_Object_Form_Form($formId);
           $pageObj = new RCMS_Object_Page_Page($pageData['id']);
			$replacedContent .= "<form name='".$formObj->getName()."' id='".$formObj->getName()."' action='".$this->_siteUrl."sys/backend_ajax/formhandler' method='POST' enctype=\"multipart/form-data\">";
			if($formObj!=null &&$formObj->getCode()!=null) {
				$replacedContent .= $formObj->getCode();
			}
          	$replacedContent .= "<input type='hidden' name='pageId' value='".$pageObj->getId()."'>";
			$replacedContent .= "<input type='hidden' name='formId' value='".$formObj->getId()."'>";
			if($captchaId != '') {
                                $replacedContent .= "<div id='captcha'>";
				$replacedContent .= "<input type='hidden' name='captchaId' value='".$captchaId."'>";
				$replacedContent .= "<img alt='' src='".$this->_siteUrl."tmp/".$captchaId.".png' id='captcha-image' style='border: medium none ; width: 200px;'/>";
				$replacedContent .= "<p><label>{%Enter the string above%}.</label></p>";
				$replacedContent .= "<p><input type='text' id='captcha-input' name='captcha[input]'/></p>";
                                $replacedContent .= "</div>";
			}
			$replacedContent .= "<p><input class='formsubmit' type='submit' value='Submit Form' /></p>";
			$replacedContent .= "</form>";
		}
		$session = new Zend_Session_Namespace($this->_siteUrl);
		$role = isset($session->currentUser) ? unserialize($session->currentUser)->getRoleId() : 0 ;
		unset($session);
		if($this->_addLinks && ($role == RCMS_Object_User_User::USER_ROLE_ADMIN || $role == RCMS_Object_User_User::USER_ROLE_SUPERADMIN) ) {
			if($formObj === null || !$formObj) {
				$replacedContent = '<a style="display:block;" href="' . $this->_siteUrl . 'sys/backend_form/addform/name/'.$containerName.'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=670&width=600" class="thickbox generator-links" title="Edit form properties">Edit form properties</a>';
			}
			else {
				$replacedContent .= '<span style="display:block;"><a href="' . $this->_siteUrl . 'sys/backend_form/editform/formId/'.$formObj->getId().'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=670&width=600" class="thickbox generator-links" title="Edit form properties">Edit form properties</a>/<a href="' . $this->_siteUrl . 'sys/backend_form/deleteform/formId/'.$formObj->getId().'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=600&width=600" onclick="return confirm(\'Do you really want to delete this form?\');" title="Delete this form">Delete Form</a></span>';
			}
		}
		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		return $translator->processScreen($replacedContent);
	}

	/**
	 * Generates main menu based on accordion
	 *
	 * @return string
	 */
	public function generateMainMenuAccordion($takeDraft = true) {
		$categories = $this->_model->getMainMenuCategories($takeDraft);
		foreach($categories as $key => $category) {
			$categories[$key]['pages'] = $this->_model->getMainMenuCategoryPages($category['categoryId']);
		}
		$this->_generatorView->sitePages = $categories;
		return $this->_generatorView->render('mainmenuaccordion.phtml');
	}

	/**
	 * Generates seo top and seo bottom variables.
	 *
	 * @param string $pageId
	 * @param string $topOrButtom
	 * @return string
	 */
	public function generateSeoVar($pageId, $topOrButtom, $isNews = false) {
		return $this->_model->getSeoVar($pageId, $topOrButtom, $isNews);
	}

	/**
	 * Generates file neede for pr scultpting.
	 * File contains json-encoded array ([page_id] => [page_url])
	 *
	 * @param string $path
	 * @param array $data
	 * @return string
	 */
	public function generatePRSFile($path, $data) {
		return @RCMS_Tools_FilesystemTools::saveFile($path . RCMS_Object_Parser_SeoParser::PFS_FILE_NAME, json_encode($data));
	}


	/**
	 * Generate Search Form
	 *
	 * Shows Search Form
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generateSearchForm($pageId) {
		if($pageId>0) {
			$pageObj = new RCMS_Object_Page_Page($pageId);
			$this->_generatorView->websiteUrl = $this->_siteUrl;
			$this->_generatorView->pageUrl = str_replace(".html", "", $pageObj->getUrl()).".html";
			return $this->_generatorView->render('searchform.phtml');
		}else {
			return "";
		}
	}

	/**
	 * Generate Search Result list
	 *
	 * @param array $searchResult
	 * @return string
	 */
	public function generateSearchResult($searchResult) {
		$pageArray = null;
		$realIdsArray = array();

		if($searchResult) {
			foreach ($searchResult as $key=>$value) {
				if(!in_array($value, $realIdsArray))
					$realIdsArray[] = $value;
			}

			foreach ($realIdsArray as $pageId) {
				$pageArray[] = new RCMS_Object_Page_Page($pageId);
			}
		}

		$this->_generatorView->pageArray = $pageArray;
		return $this->_generatorView->render('searchresult.phtml');
	}

	/**
	 * Generate Search Result list with page preview image
	 *
	 * @param array $searchResult
	 * @return string
	 */
	public function generateSearchResultImg($searchResult) {
		$pageArray = null;
		$realIdsArray = array();

		if($searchResult) {
			foreach ($searchResult as $key=>$value) {
				if(!in_array($value, $realIdsArray))
					$realIdsArray[] = $value;
			}

			foreach ($realIdsArray as $pageId) {
				$pageArray[] = $this->_model->selectPageWithImageByPageId($pageId);
			}
		}
		$this->_generatorView->pageArray = $pageArray;
		return $this->_generatorView->render('searchresultimg.phtml');
	}

	/**
	 * Generate plugin
	 *
	 * @param string $name
	 * @param array $options
	 * @param array $pageData
	 * @return string
	 */
	public function generatePluginContent($name, $options, $pageData) {
		if($name) {
			$name = strtolower($name);
			$pluginData = $this->_model->selectPluginByName($name);
			if(is_array($pluginData) && !empty($pluginData)) {
				if($pluginData['status'] != self::PLUGIN_ENABLED) {
					return 'Plugin <strong>' . $name . '</strong> is not enabled.';
				}
				if(empty ($pageData)) {
					$pageData = array('websiteUrl' => $this->_siteUrl);
				}
				try {
					$plugin = RCMS_Core_PluginFactory::createPlugin($name, $options, $pageData);
					return $plugin->run();
				}
				catch (Exception $e) {
					return $e->getMessage();
				}
			}
			else {
				return 'Plugin <strong>' . $name . '</strong> is not installed.';
			}
		} else {
			return 'Plugin name is not specified';
		}
	}

	public function generateSwapper($params, $id) {
		if (empty($params) || !isset($params['name']) || !is_array($params['options'])) {
			return '' ;
		}
		$folder = trim($params['name']);
		$pathFolder = $this->_sitePath . 'images/' . $folder . '/';
		if ($folder === '' || !is_dir($pathFolder) || !is_dir($pathFolder . 'original/')) {
			return '';
		}
		$this->_generatorView->folder = $folder;
		$this->_generatorView->slideshow = (isset($params['options'][0])?intval($params['options'][0]):1);
		$this->_generatorView->time = (isset($params['options'][1])?intval($params['options'][1])*1000:2000);

		$width = $params['options'][2];

		//d($params['options'],false);
		if(isset($params['options'][3])) {
			$height = $params['options'][3];
		}else {
			if(isset($params['options'][2])){
			$height = $params['options'][2];
			}else{
				$height = $width;
			}
		}

		$this->_generatorView->desiredWidth = $width;
		$this->_generatorView->desiredHeight = $height;
		$imgPresets = $this->_model->getConfigImagesPresets();
		if($width > 0 && $width <= $imgPresets['small']) {
			$this->_generatorView->sourceFolder = '/small/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'small/');
		}
		elseif($width >= $imgPresets['small'] && $width <= $imgPresets['medium']) {
			$this->_generatorView->sourceFolder = '/medium/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'medium/');
		}
		elseif($width >= $imgPresets['medium'] && $width <= $imgPresets['large']) {
			$this->_generatorView->sourceFolder = '/large/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'large/');
		}
		elseif($width >= $imgPresets['large'] || $width == 0) {
			$this->_generatorView->sourceFolder = '/original/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'original/');
		}
		//$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'original/');
		$this->_generatorView->uniqueId = $id;
		$this->_generatorView->url = $this->_siteUrl;
		return $this->_generatorView->render('swapper.phtml');
	}

	public function generateRegularNewsList($name, $options, $data) {
		$newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->newsFolder = ($newsFolder) ? $newsFolder : 'news';
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$newsCategoriesArray = $this->_model->selectAllNewsCategories();
		$newsArray = $this->_model->selectAllNews();
		$newsArrayWithoutCategory = $this->_model->selectAllNews(0);
		switch($name) {
			case 'all':
				foreach ($newsArray as &$news) {
					$news['newsDate'] = $this->processNewsDate($news['newsDate']);
				}
				foreach ($newsArrayWithoutCategory as &$news) {
					$news['newsDate'] = $this->processNewsDate($news['newsDate']);
				}
				$this->_generatorView->newsCategoriesArray = $newsCategoriesArray;
				$this->_generatorView->newsArray = $newsArray;
				$this->_generatorView->newsArrayWithoutCategory = $newsArrayWithoutCategory;
				return $this->_generatorView->render('newslist.phtml');
				break;
			case 'archived':
				$archivedNews = array();
				foreach ($newsArray as $newsItem) {
					if($newsItem['newsArchived']) {
						$archivedNews[] = $newsItem;
					}
				}
				$this->_generatorView->news = $archivedNews;
				return $this->_generatorView->render('newslistarchived.phtml');
				break;
			default:
				$catId = 0;
				foreach ($newsCategoriesArray as $newsCatItem) {
					if($newsCatItem['newsCategoryName'] == $name) {
						$this->_generatorView->categoryName = $name;
						$catId = $newsCatItem['newsCategoryId'];
						break;
					}
				}
				$this->_generatorView->categoryNews = $this->_model->selectAllNews($catId);
				return $this->_generatorView->render('newslistbycat.phtml');
				break;
		}
	}

	public function generateNewsFolderUrl() {
		$result = $this->_model->selectDefaultNewsFolder();
		if($result && !empty($result['default_news_folder'])) {
			return $this->_siteUrl.$result['default_news_folder']."/";
		}else {
			return $this->_siteUrl."news/";
		}
	}

	/**
	 * Generates list of pages for given category name
	 *
	 * If there is no category with such name returns false
	 * If there are no pages in the category returns empty array
	 *
	 * @param string $categoryName
	 * @param boolean $withImg tells generator that result should include pages thumbnails
	 */
	public function generateListPages($categoryName, $withImg) {

		if(is_array($withImg) && isset($withImg[0])) {
			$withImg = ($withImg[0] == 1) ? true : false;
		}
		elseif($withImg !== true) {
			$withImg = false;
		}
		$categoryId = $this->_model->getCategoryIdByName($categoryName);
		if(!$categoryId) {
			return 'There is no category with such name: '. $categoryName . '!';
		}
		if($withImg) {
			$pages = $this->_model->getCategoryPagesListImg($categoryId);
			$this->_generatorView->categoryPagesListImg = $pages;
			return $this->_generatorView->render('catpageslistimg.phtml');
		}
		else {
			$pages = $this->_model->getCategoryPagesList($categoryId);
			$this->_generatorView->categoryPagesList = $pages;
			return $this->_generatorView->render('catpageslist.phtml');
		}

	}

	/**
	 * Generate new item varriable
	 *
	 * @param string $newsTitle
	 * @param array $options
	 * @param array $newsData
	 * @return string
	 */
	public function generateSocialBookmarksBlock($pageData) {
	//$pageUrl,
		$pageTitle = $pageData['header_title'];
		$websiteUrl = $pageData['websiteUrl'];
		$pageUrl = $websiteUrl.$pageData['url'].".html";
		//d($pageUrl);

		$this->_generatorView->pageTitle = $pageTitle;
		$this->_generatorView->websiteUrl = $websiteUrl;
		$this->_generatorView->pageUrl = $pageUrl;
		return $this->_generatorView->render('socialmarks.phtml');
	}

	function generateNewsAggregatorBlock($pageData) {
		$websiteUrl = $pageData['websiteUrl'];
		$xmlFilesArray = RCMS_Tools_FilesystemTools::findFilesByExt('feeds/', 'xml');
		if(in_array('all.xml', $xmlFilesArray)) {
			$rssUrl = $websiteUrl.'feeds/'.RCMS_Object_QuickConfig_QuickConfig::$allNewsXmlName.'.xml';
			$this->_generatorView->rssUrl = $rssUrl;
			return $this->_generatorView->render('newsaggregator.phtml');
		}
		else {
			return '';
		}
	}

	public function cutDescription($string, $length = 200) {
		if (empty ($string)){
			return false;
		}
		$length = intval($length);
		if (extension_loaded('mbstring')){
			mb_internal_encoding('UTF-8');
			$encoding = mb_detect_encoding($string);
			if (mb_strlen($string) <= $length){
				return $string;
			}
			return mb_substr($string, 0, $length, $encoding) . '...';
		} else {
			error_log('[seotoaster]: Mbstring extension not loaded');
			$string = RCMS_Tools_FilesystemTools::normalize($string, false);
			if (strlen($string) <= $length){
				return $string;
			}
			return substr($string, 0, $length) . '...';
		}
	}

	public function processNewsRssDate($date) {
		$tmp = explode(" ",$date);
		return $tmp[0]." ".$tmp[1]." ".$tmp[2]." ".$tmp[3];
	}

	public function processAtomRssDate($date) {
		$tmp = explode("-",$date);
		$year = $tmp[0];
		$month = $tmp[1];
		$day = substr($tmp[2], 0,2);
		$resDate = date("D, j M Y",mktime(0, 0, 0, $month, $day, $year));
		return $resDate;
	}

	public function generateExternalRSS($url, $options, $data) {
		if(trim($url) == '' || !$url) {
			return 'Wrong rss feed url';
		}
		$url = str_replace(' ', '%20', $url);
		$url = str_replace('|', '%7C', $url);
		$url = str_replace('&amp;', '&', $url);
		try {
			//$newsRssFeedChannel = new Zend_Feed_Rss('http://' . $url);
			$newsRssFeedChannel = Zend_Feed_Reader::import('http://' . $url);
		}
		catch(Zend_Feed_Exception $zfe) {
			return $zfe->getMessage();
		}
		catch (Exception $e) {
			return $e->getMessage();
		}
		$newsRss             = array();
		$countResult         = (intval($options[0])) ? intval($options[0]) : 4 ;
		$maxCharacters       = (isset($options[1])) ? trim($options[1]) : '';
		$showFullDescription = !intval($maxCharacters);
		foreach ($newsRssFeedChannel as $item) {
			$description = $item->getDescription();
			$newsRss[] = array(
				'title'       => $item->getTitle(),
				'link'        => $item->getLink(),
				'description' => ($showFullDescription) ? $description : $this->cutDescription($description, $maxCharacters),
				'pubDate'     => $item->getDateModified()
			);
		}
		$this->_generatorView->countResult = $countResult;
		$this->_generatorView->newsRss = $newsRss;
		return $this->_generatorView->render('xrss.phtml');
	}

	public function sendRssCURL($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,html_entity_decode($url));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_REFERER, "www.seotoaster.com");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//curl_setopt($ch, CURLOPT_POST, 'application/x-www-form-urlencoded');
		/*curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);*/
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}

    public function generateProductContent($id, $preview = false)
    {
        if ($id <= 0 ) {
            return '';
        }
        $product = new RCMS_Object_Product_Product($id);
        if ($product->getId() > 0) {
            return $this->_generateTemplateForProduct($product, $preview);
        }
        return '';
    }

    public function generateProductListContent($params)
    {
        /* generate string of query where parameters separates the symbol ':' */
        $str = '';
        if (isset($params['name'])) {
            $str .= trim($params['name']);
        }
        if (isset($params['options']) && count($params['options']) > 0) {
            if ($str == '') {
                $str .= implode(':', $params['options']);
            } else {
                $str .= ':'.implode(':', $params['options']);
            }
        }
        if ($str == '') {
            return '';
        }
        /* obtain an array of parameters */
        $data = explode(':', $str);
        $order = array();
        $brands = array();
        $categories = array();

        /* parse parameters */
        foreach ($data as $d) {
            $options =  explode('-', trim($d,','));
            if (!isset($options[0]) || !isset($options[1])) {
                continue;
            }
            switch (trim($options[0])) {
                case 'order':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        foreach ($tmp as $tmpVal) {
                            $tmpVal = trim($tmpVal);
                            if ($tmpVal == 'name' || $tmpVal == 'brand' || $tmpVal == 'price') {
                                $order[] = $tmpVal;
                            }
                        }
                    }
                    break;
                case 'brands':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        $brands = $tmp;
                    }
                    break;
                case 'categories':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        $categories = $tmp;
                    }
                    break;
                default:
                    break;
            }
        }
        $products = array();

        /* if we don't have categories, we got products by brand */
        if (count($categories) == 0) {
            if (count($brands) > 0) {
                foreach ($brands as $brand) {
                    $brand = trim($brand);
                    if ($brand == '') {
                        continue;
                    }
                    $result = $this->_model->selectProductsByBrandName($brand);
                    if (is_array($result) && count($result) > 0 ) {
                        $products = array_merge($products, $result);
                    }
                }
            }
        } else {
            if (count($categories) > 0) {
                foreach ($categories as $category) {
                    $category = intval($category);
                    if ($category <= 0) {
                        continue;
                    }
                    $result = $this->_model->selectProductsByGroupId($category);
                    if (is_array($result) && count($result) > 0 ) {
                        $products = array_merge($products, $result);
                    }
                }
                /* filter by brand */
                if (count($brands) > 0 && count($products) > 0) {
                    $tmp = array();
                    foreach ($products as $prod) {
                        if (in_array($prod['brand'], $brands)) {
                            $tmp[] = $prod;
                        }
                    }
                    if (count($tmp) > 0) {
                        $products = $tmp;
                    }
                }
            }
        }

        /* removes duplicate a product */
        $tmp = $products;
        foreach ($products as $key1 => $val1) {
            $c = 0;
            foreach ($tmp as $key2 => $val2) {
                if ($val1['id'] == $val2['id']) {
                    $c++;
                    if ($c >= 2) {
                        unset($products[$key1]);
                        unset($tmp[$key2]);
                    }
                }
            }
        }

        if (count($products) <= 0) {
            return '';
        }

        /* make arrays for sorting */
        $price = $brand = $name = array();
        foreach ($products as $dataProduct) {
           $brand[] = $dataProduct['brand'];
           $price[] = $dataProduct['price'];
           $name[] = $dataProduct['name'];
        }

        /* sorting */
        $countOrder = count($order);
        switch ($countOrder) {
            case '1':
                array_multisort($$order[0], $products);
                break;
            case '2':
                array_multisort($$order[0], $$order[1], $products);
                break;
            case '3':
                array_multisort($$order[0], $$order[1], $$order[2],$products);
                break;
            default:
                sort($products);
                break;
        }

        /* generate the content for list product */
        $content = '';
        foreach ($products as $item) {
            $product = new RCMS_Object_Product_Product($item['id']);
            $content .= $this->_generateTemplateForProduct($product);
            unset ($product);
        }
        return $content;
    }

    private function _generateTemplateForProduct(RCMS_Object_Product_Product $product, $preview = false)
    {
        $template = '';
        $result = false;

        if ($preview) {
            $result = $this->_model->selectTemplateForProduct('template_product');
            if (is_array($result) && isset($result['template_product']['value'])) {
                $template = $result['template_product']['value'];
            }
        } else {
            $result = $this->_model->selectTemplateForProduct('template_prod_list');
            if (is_array($result) && isset($result['template_prod_list']['value'])) {
                $template = $result['template_prod_list']['value'];
            }
        }
        if ($template == '') {
            return '';
        }
        //$currency = $result['currency']['value'];
        $shoppingConfig     = $this->_model->selectShoppingConfig();
        $currency           = $shoppingConfig['currency'];
        $shipping           = unserialize($shoppingConfig['shipping_general']);
        $weightUnits        = $shipping['weight-units'];

        /* got categories */
        $categories = '';
		//selection the url of categorie landing page
		$landingCategoriesUrl = $this->_model->selectLandingUrl(RCMS_Object_Page_Page::P_OPT_PRODCATLANDING);
		$landingBrandsUrl = $this->_model->selectLandingUrl(RCMS_Object_Page_Page::P_OPT_PRODBRANDLANDING);
        foreach ($product->getGroups() as $group) {
			if($landingCategoriesUrl) {
				$categories .= '<a href="' . $this->_siteUrl . $landingCategoriesUrl . '.html" title="' . $group['name'] . '">' . $group['name'].'</a>, ';
			}
			else {
				//$categories .= $group['name'].', ';
				$categories .= RCMS_Tools_Tools::convertEncoding($group['name']) . ', ';
			}
        }
        $categories = rtrim($categories, ', ');

        /* got related */
        $relatedIds = explode(',', $product->getRelated());

        /* got options */
        $options = explode('###', $product->getOptions());
        if (trim($options[count($options)-1]) == '') {
            unset ($options[count($options)-1]);
        }
        $optionsContent = '';
        if (count($options) > 0) {
            foreach ($options as $option) {
                $option = str_replace(':::', ' : ', $option);
                $optionsContent .= '<span class="option">'.$option.'</span>';
            }
        }
        /* link to page */
        $link = '';
        $page = new RCMS_Object_Page_Page($product->getPageId());
        if ($page->getId() > 0 && $page->getUrl() != '') {
            $link = $this->_siteUrl . trim($page->getUrl()) . '.html';
        }
        unset ($page);

        /* link to original of image */
        $zoomImage =  str_replace('/small/', '/original/', $this->_siteUrl.$product->getPhoto());

        /* link for edit product */
        $linkToEditProduct = '';
        if ($this->_addLinks) {
            $linkToEditProduct = '<button class="formsubmit" onclick="tb_show(\'\',\''.$this->_siteUrl.'sys/backend_shopping/product/id/'.$product->getId().'/?TB_iframe=true&height=525&width=845\',\'\');">Edit this product</button>';
        }

        /* photo of product */
        $photo = '';
        if ($preview) {
            $photo = $this->_siteUrl.str_replace('/small/', '/medium/', $product->getPhoto());
        } else {
            $photo = $this->_siteUrl.$product->getPhoto();
        }

        /* parser variables */
        $template = str_replace('{brand}', ($landingBrandsUrl) ? '<a href="' . $this->_siteUrl . $landingBrandsUrl . '.html" title="' . $product->getBrand() . '">' . $product->getBrand() . '</a>' : RCMS_Tools_Tools::convertEncoding($product->getBrand()), $template);
        $template = str_replace('{categories}', $categories, $template);
        $template = str_replace('{photo}', $photo, $template);
        $template = str_replace('{itemid}', $product->getItemId(), $template);

        $addTax = 1;
        if ($product->getTax() > 0 && isset($shoppingConfig['show-price-ati']) && $shoppingConfig['show-price-ati']=='1'){
            $shipping = new RCMS_Object_Shipping_Shipping();
            $shippingAddress = $shipping->getShippingAddress();
            unset($shipping);

            if (!empty($shippingAddress)){
                $location = array('country'=>$shippingAddress['country'],'state'=>$shippingAddress['state']);
            } else {
                $location = array('country'=>$shoppingConfig['country'],'state'=>$shoppingConfig['state']);
                $defaultTaxRule = unserialize($shoppingConfig['default_tax_rule']);
            }

            if (!empty ($defaultTaxRule)){
                $addTax = 1+$defaultTaxRule['tax'][$product->getTax()]/100;
            } else {
                $taxRules = unserialize($shoppingConfig['tax-rules']);
                foreach ($taxRules as $rule) {
                    if (
                            ($rule['zone']==$location['country'] && in_array($location['state'],  explode(',', $rule['subzone']))) ||
                            (($location['state']=='' || $location['state']=='null') && in_array($location['country'],explode(',',$rule['subzone'])))
                       )
                    {
                        $addTax = 1+$rule['tax'][$product->getTax()]/100;
                        break;
                    }
                }
            }
        }
		if ($product->getOldPrice() && ($product->getPrice() != $product->getOldPrice())) {
			$priceReplace = '<strike>' . number_format(($product->getOldPrice() * $addTax),2,'.','') . ' ' . $currency . '</strike>';
			$template = str_replace('{onsale}', '<span class="price onsale">' . number_format(($product->getPrice() * $addTax),2,'.','') . ' ' . $currency . '</span>', $template);
		}
		else {
			$priceReplace = number_format((($product->getPrice() > 0 ? $product->getPrice() : $product->getOldPrice()) * $addTax), 2, '.', '' ) . ' ' . $currency;
			$template = str_replace('{onsale}', '', $template);
		}
        $template = str_replace('{price}', $priceReplace, $template);
        $template = str_replace('{weight}',$product->getWeight() . ' ' . $weightUnits, $template);
        $template = str_replace('{name}', $product->getName(), $template);

		$template = str_replace('{description}', nl2br(RCMS_Tools_Tools::convertEncoding($product->getDescription())), $template);
		$template = str_replace('{fulldescription}', nl2br(RCMS_Tools_Tools::convertEncoding($product->getFullDescription())), $template);
		$template = str_replace('{mpn}', $product->getMpn(), $template);
        $template = str_replace('{related}', $this->generateRelatedProducts($relatedIds), $template);
        $template = str_replace('{related_img}', $this->generateRelatedProducts($relatedIds,true), $template);
        $template = str_replace('{options}', $this->_generateOptionsContent($options, $product->getId()), $template);
        $template = str_replace('{url}', RCMS_Tools_Tools::convertEncoding($link), $template);
		$template = preg_replace(array('/\{addtocart\}/','/\{addtocartamount\}/'), array($this->_generateAddToCartWidget($product->getId()),$this->_generateAddToCartWidget($product->getId(),true)),$template,1);
        $template = str_replace('{zoomimage}', $zoomImage, $template);
        $template = str_replace('{editproduct}', $linkToEditProduct, $template);
        $template = str_replace('{quote_form}', ($preview == true ? $this->generateInstantQuoteForm($product->getId()) : ' '), $template);
        $template = str_replace('{starrating}', ($preview == true ? $this->_generateStarRatingWidget($product): ' '), $template);
        $template = str_replace('{freebies}', ($preview == true && $product->getOldPrice() ? $this->_generateFreebiesWidget($product->getFreebies(), $product->getSaleDue()): ' '), $template);
        if ($preview){
            if (preg_match('/\{review(_moderated)?\}/',$template,$matches)){
                switch ($matches[0]){
                    case '{review}':
                        $template = preg_replace('/\{review\}/', $this->_generateReviewsList($product), $template,1);
                        break;
                    case '{review_moderated}':
                        $template = preg_replace('/\{review_moderated\}/', $this->_generateReviewsList($product, true), $template,1);
                        break;
                    default:
                        break;
                }
            }
        }
        $translator = new RCMS_Object_Parser_LanguageParser();
        return $translator->processScreen($template);
    }

	private function _generateOptionsContent($options, $productId) {
		$forSelects  = array();
		$htmlContent = '';
		foreach ($options as $key => $option) {
			$explodedOption = explode(':::', $option);
			$forSelects[$key]['label']   = trim($explodedOption[0]);
			$forSelects[$key]['options'] = explode(',', $explodedOption[1]);
		}
		//making html
		if(sizeof($forSelects) > 0) {
			$this->_generatorView->forSelects = $forSelects;
			$this->_generatorView->productId  = $productId;
			$content = $this->_generatorView->render('itemoptions.phtml');
			return $content;
		}
		return '';
	}

	public function generateQuoteContent(RCMS_Object_Quote_Quote $quote, RCMS_Object_Shopping_ShoppingUserCart $userCart, $tax) {
		$totalPrice = 0;

        $shoppingConfig = $this->_model->selectShoppingConfig();
		$cartData = $userCart->getCartData();
		foreach($cartData as $key => $value) {
			$totalPrice += $value['price'] * $value['count'];
		}
        if ($shoppingConfig['shipping_type'] != 'pickup') {
            $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
            $this->_generatorView->shipping = number_format($shipping->getShippingCost(),2,'.','');
            $shippingAddress = $shipping->getShippingAddress();
            if (!empty($shippingAddress)) {
                $this->_generatorView->shippingAddress = $shippingAddress;
            }
        }
        // localizating date formats
        $locale = Zend_Locale::getLocaleToTerritory($shoppingConfig['country']);
        $quoteDate  = new Zend_Date(strtotime($quote->getDate()), $locale);
        $quoteValid = new Zend_Date(strtotime($quote->getValidUntilDate()), $locale);
		$this->_generatorView->shoppingConfigData = $shoppingConfig;
        $this->_generatorView->sitePath         = $this->_sitePath;
		$this->_generatorView->userName         = $userCart->getName();
		$this->_generatorView->userEmail        = $userCart->getEmail();
        $this->_generatorView->userPhone        = $userCart->getPhone();
        $this->_generatorView->userZip          = $userCart->getZip();
        $this->_generatorView->userAddress1     = $userCart->getAddress1();
        $this->_generatorView->userAddress2     = $userCart->getAddress2();
        $this->_generatorView->userCity         = $userCart->getCity();
        $this->_generatorView->userState        = $userCart->getState();
        $this->_generatorView->userCountry      = $userCart->getCountry();
        $this->_generatorView->userCompany      = $userCart->getCompany();
		$this->_generatorView->totalPrice       = $totalPrice;
        $this->_generatorView->showATI          = isset($shoppingConfig['show-price-ati'])?$shoppingConfig['show-price-ati']:null;
        $this->_generatorView->totalTax         = $tax['total'];
        $this->_generatorView->taxes	        = $tax;
        $this->_generatorView->validUntil       = $quoteValid->get(Zend_Locale_Format::getDateFormat($locale));
        $this->_generatorView->validTimestamp	= $quoteValid->getTimestamp();
        $this->_generatorView->discount         = $quote->getDiscount();
		$this->_generatorView->quoteName        = $quote->getName();
		$this->_generatorView->quoteDate        = $quoteDate->get(Zend_Locale_Format::getDateFormat($locale));
		$this->_generatorView->quoteDisclaimer  = $quote->getDisclaimer();
        $this->_generatorView->quoteId          = $quote->getId();
        $this->_generatorView->cartData         = $userCart->getCartData();

        $content = $this->_generatorView->render('quote.phtml');

        $parser = new RCMS_Object_Parser_Parser($content, '', false);

		return $parser->processContent();
	}

	public function generateQuoteMailToUser($quoteId) {
		$this->_generatorView->qid          = $quoteId;
		$this->_generatorView->websiteUrl   = $this->_siteUrl;
                $this->_generatorView->contactInfo  = $this->_model->selectShoppingConfig();
		return $this->_generatorView->render('quotemailtouser.phtml');
	}

        public function generateQuoteResponderBody() {
                $this->_generatorView->websiteUrl   = $this->_siteUrl;
                $this->_generatorView->contactInfo  = $this->_model->selectShoppingConfig();
                return $this->_generatorView->render('quoteresponderbody.phtml');
        }

        public function generateQuoteMailToAdmin($userInfo, $quoteId = false) {
                $this->_generatorView->websiteUrl = $this->_siteUrl;
                $this->_generatorView->userInfo   = $userInfo;
                $this->_generatorView->quoteId	  = $quoteId;
				return $this->_generatorView->render('quotemailtoadmin.phtml');
        }

	/**
	 * Generate cart widget which shows how many items in user's shopping cart
	 *
	 */
	public function generateCartWidget() {
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$this->_generatorView->itemsCount = $shoppingCart->getItemsCountForCart();
		//$this->_generatorView->totalPrice = $shoppingCart->getTotalPrice();
		$shoppingConfigData = $this->_model->selectShoppingConfig();
        $this->_generatorView->currency  = $shoppingConfigData['currency'];
        if (isset($shoppingConfigData['show-price-ati']) && $shoppingConfigData['show-price-ati'] == '1'){
            $taxRule = unserialize($shoppingConfigData['default_tax_rule']);
            if (empty ($taxRule)){
                $rules = unserialize($shoppingConfigData['tax-rules']);
                foreach ($rules as $rule) {
                    if ( ($rule['zone']==$shoppingConfigData['country'] && in_array($shoppingConfigData['state'],  explode(',', $rule['subzone']))) ||
                         ($shoppingConfigData['state']=='' && in_array($shoppingConfigData['country'],explode(',',$rule['subzone']))) )
                    {
                        $taxRule = $rule;
                        break;
                    }
                }
            }
            $this->_generatorView->totalPrice = $shoppingCart->getTotalPrice(true, $taxRule);
        } else {
            $this->_generatorView->totalPrice = $shoppingCart->getTotalPrice();
        }
        if ($shoppingConfigData['shipping_type'] == 'amount') {
            $this->_generatorView->freeShipping = unserialize($shoppingConfigData['shipping_general']);
            $this->_generatorView->storeCountry  = $shoppingConfigData['country'];
        }
		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		return $translator->processScreen($this->_generatorView->render('cart.phtml'));
	}

	public function generateConcatCss($pageData) {
		if(file_exists($pageData['templateTheme'] . '/concat.css')) {
			return true;
		}
		return RCMS_Tools_Tools::createConcatCss($pageData['templateTheme']);
	}

	public function generateFeaturedPageContent($pageId, $options) {
		$withImage = $options[0];
		$limit     = (int)$options[1];
		$this->_generatorView->featuredPageData = $this->_model->getFeaturedPageData($pageId, $withImage);
		$this->_generatorView->featuredPageData['description'] = substr($this->_generatorView->featuredPageData['description'],0,$limit);
		$this->_generatorView->withImage = (bool)$withImage;
		return $this->_generatorView->render('featuredpage.phtml');
	}

	public function generateRobotsTxt($sitemapUrl) {
		$this->_generatorView->sitemapUrl = $sitemapUrl;
		$robotsTxtContent = $this->_generatorView->render('robotstxt.phtml');
		if(RCMS_Tools_FilesystemTools::isFileExists('robots.txt')) {
			try {
				RCMS_Tools_FilesystemTools::saveFile('robots.txt', $robotsTxtContent);
			}
			catch (Exception $e) {
				return false;
			}
			return true;
		}
		return false;
	}

	public function generateMemberLoginForm() {
		if($this->_memberLogged) {
			return '';
		}
		//for translator
		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		return $translator->processScreen($this->_generatorView->render('memberlogin.phtml'));
	}

	public function generateMemberLogout() {
		if(!$this->_memberLogged) {
			return '';
		}
		$translator = new RCMS_Object_Parser_LanguageParser($this->_languageId);
		return $translator->processScreen($this->_generatorView->render('memberlogout.phtml'));
		//return '<a href="javascript:;" onclick="document.location.href=\'' . $this->_siteUrl . 'sys/login/memberlogout\'">Logout</a>';
	}

	private function _addLinks($contentType, $containerName, $containerId = '', $pageId = 0, $add = false) {
		if($this->_addLinks && !$this->_memberLogged) {
			switch ($contentType) {
				case RCMS_Object_Container_Container::C_TYPE_CONTENT:
					if($add) {
						$replacedContent = '<a title="Click to edit content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcontent/name/' . $containerName . '/pageId/' . $pageId . '/?TB_iframe=true&height=600&width=940\',\' \');" class="generator-links"><img alt="edit content" src="' . $this->_siteUrl . 'system/images/editadd.png" /></a>';
					}
					else {
						$replacedContent = '<a title="Click to edit content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcontent/id/'.$containerId.'/?TB_iframe=true&height=600&width=940\',\' \');" class="generator-links"><img alt="edit content" src="' . $this->_siteUrl . 'system/images/editadd.png" /></a>';
					}
				break;
				case RCMS_Object_Container_Container::C_TYPE_STATIC:
					if($add) {
						$replacedContent = '<a title="Click to edit static content" href="javascript:;"  onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcontent/name/'.$containerName.'/type/2?TB_iframe=true&height=600&width=940\',\' \')"   class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-content.png" alt="edit static content" /></a>';
					}
					else {
						$replacedContent = '<a title="Click to edit static content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcontent/id/'.$containerId.'/?TB_iframe=true&height=600&width=940\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-content.png" alt="edit static content" /></a>';
					}
				break;
				case RCMS_Object_Container_Container::C_TYPE_HEADER:
					if($add) {
						$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addheader/name/'.$containerName.'/pageId/'.$pageId.'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-header.png" alt="edit header" /></a>';
					}
					else {
						$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editheader/id/'.$containerId.'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-header.png" alt="edit header" /></a>';
					}
				break;
				case RCMS_Object_Container_Container::C_TYPE_STATICHEADER:
					if($add) {
						$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addheader/name/'.$containerName.'/type/5?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-header.png" alt="edit static header" /></a>';
					}
					else {
						$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editheader/id/'.$containerId.'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-header.png" alt="edit static header" /></a>';
					}
				break;
				case RCMS_Object_Container_Container::C_TYPE_CODE:
					if($add) {
						$replacedContent = '<a title="Click to edit code" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcode/name/'.$containerName.'/pageId/'.$pageId.'/?TB_iframe=true&height=460&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-code.png" alt="edit code" /></a>';
					}
					else {
						$replacedContent = '<a title="Click to edit code" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcode/id/'.$containerId.'/?TB_iframe=true&height=460&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-code.png" alt="edit code" /></a>';
					}
				break;
				case RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP:
					if($add) {
						$replacedContent = '<a title="Click to add google map" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addgooglemap/name/'.$containerName.'/type/'.RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP.'?TB_iframe=true&height=360&width=535\',\' \')" class="generator-links">Add Google Map Code</a>';
					}
					else {
						$replacedContent = '<a title="Click to edit google map" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editgooglemap/id/'.$containerId.'/?TB_iframe=true&height=360&width=535\',\' \')" class="generator-links">Edit Google Map Code</a>';
					}
				break;
			}
			return $replacedContent;
		}
		return '';
	}

	private function _wrapUnPublished($content) {
		return '<div class="border_red">' . $content . '<p style="clear:both;"/></div>';
	}

        /**
	 * Generate Cooliris Wall widget
	 *
	 * @param array $params
	 * @return string
	 */
        public function generateCoolirisWidget($params)
        {
            $name = isset($params['name']) ? trim($params['name']) : '';
            $path = $this->_sitePath.'images/'.$name.'/';
            if ($name == '' || !is_dir($path)) {
                return '';
            }
            $originalImages = RCMS_Tools_FilesystemTools::scanDir($path.'original/');
            if ($originalImages === false || (is_array($originalImages) && count($originalImages) <= 0)) {
                return '';
            }
            $xmlRssForCooliris = $this->_getXmlRssForCooliris($name, $originalImages, 'small');
            @file_put_contents($path.'/'.$name.'.xml', $xmlRssForCooliris);

            $this->_generatorView->name = $name;
            $this->_generatorView->coolirisWidth = isset($params['options'][0]) ? intval(trim($params['options'][0])) : 600;
            $this->_generatorView->coolirisHeight = isset($params['options'][1]) ? intval(trim($params['options'][1])) : 450;
            $this->_generatorView->coolirisRows = isset($params['options'][2]) ? intval(trim($params['options'][2])) : 3;
            $this->_generatorView->coolirisStyle = isset($params['options'][3]) && in_array(trim($params['options'][3]), array('white','black','light','dark')) ? trim($params['options'][3]) : 'white';
            return $this->_generatorView->render('cooliriswall.phtml');
        }

    public function generateBlogPosts($params)
    {
        $sort = '';
        if (isset($params['name'])) {
            switch ($params['name']) {
                case 'date':
                    $sort = 'container.publishing_date DESC';
                    break;
                case 'author':
                    $sort = 'user.nickname ASC';
                    break;
                default:
                    break;
            }
        }
        /*$month1 = isset($params['options'][0]) ? intval($params['options'][0]) : 0;
        $month2 = isset($params['options'][1]) ? intval($params['options'][1]) : 0;*/

        $date1 = isset($params['options'][0]) ? $params['options'][0] : 0;
        $date2 = isset($params['options'][1]) ? $params['options'][1] : 0;
        $userId = isset($params['options'][2]) ? intval($params['options'][2]) : 0;
        $where = "content.blog = '1'".($userId > 0 ? " AND container.user_id = $userId" : '');
        $tmpDate1 = explode('-', $date1);
        $tmpDate2 = explode('-', $date2);

        if (count($tmpDate1) == 3 && count($tmpDate2) == 3 && $tmpDate2[0] >= $tmpDate1[0]  && $tmpDate2[1] >= $tmpDate2[1] && $tmpDate2[2] > $tmpDate1[2]) {
            $where .= ' AND YEAR(\''.$date1.'\') <= YEAR(container.publishing_date) AND YEAR(\''.$date2.'\') >= YEAR(container.publishing_date)';
            $where .= ' AND MONTH(\''.$date1.'\') <= MONTH(container.publishing_date) AND MONTH(\''.$date2.'\') >= MONTH(container.publishing_date)';
            $where .= ' AND DAY(\''.$date1.'\') <= DAY(container.publishing_date) AND DAY(\''.$date2.'\') >= DAY(container.publishing_date)';
        }
        /*if ($month2 - $month1 > 0) {
            $where .= " AND YEAR(CURRENT_DATE) = YEAR(container.publishing_date) AND MONTH(container.publishing_date) >= $month1 AND MONTH(container.publishing_date) <= $month2";
        }*/
        $posts = $this->_model->selectPostList($sort, $where);

        if (empty($posts)) {
            return '';
        }
        foreach ($posts as $key => $post) {
            $page = new RCMS_Object_Page_Page($post['page_id']);
            if ($page->getId() > 0) {
                $posts[$key]['url'] = $this->_siteUrl.$page->getUrl().'.html';
            } else {
                $posts[$key]['url'] = '#';
            }
            unset ($page);
        }
        $this->_generatorView->maxCharacters = isset($params['options'][3]) ? intval($params['options'][3]) : 300;
        $this->_generatorView->posts = $posts;
		return $this->_generatorView->render('bloglistposts.phtml');
    }

    public function generateGalleryForFolderImages(array $params)
    {
        $folder = isset($params['name']) ? trim($params['name']) : '';
        $thumbnails = isset($params['options'][0]) ? intval(trim($params['options'][0])) : 0;
        $crop = isset($params['options'][1]) && $params['options'][1] == '1' ? true : false;
        $caption = isset($params['options'][2]) && $params['options'][2] == '1' ? true : false;
        $cooliris = isset($params['options'][3]) && $params['options'][3] == '1' ? true : false;
        $path = $this->_sitePath.'images/'.$folder.'/';
        $useFolder = 'thumbnails';

        if ($folder == '' || !is_dir($path) || $thumbnails <= 0) {
            return '';
        }

        $originalImages = RCMS_Tools_FilesystemTools::scanDir($path.'original/');
        if ($originalImages === false || (is_array($originalImages) && count($originalImages) <= 0)) {
            return '';
        }
        // if use crop
        if ($crop) {
            $useFolder = 'crop';
            if (!is_dir($path.'crop/')) {
                @mkdir($path.'crop/', '0755');
            }
            foreach ($originalImages as $originalImage) {
                if (is_file($path.'crop/'.$originalImage)) {
                    $infoImg = getimagesize($path.'crop/'.$originalImage);
                    if ($infoImg[0] != $thumbnails) {
                        RCMS_Tools_Tools::cropImage($thumbnails, $thumbnails, $path.'original/'.$originalImage, $path.'crop/'.$originalImage);
                    }
                } else {
                    RCMS_Tools_Tools::cropImage($thumbnails, $thumbnails, $path.'original/'.$originalImage, $path.'crop/'.$originalImage);
                }
            }
        } else {
            if (!is_dir($path.'thumbnails/')) {
                @mkdir($path.'thumbnails/', '0755');
            }
            foreach ($originalImages as $originalImage) {
                if (is_file($path.'thumbnails/'.$originalImage)) {
                    $infoImg = getimagesize($path.'thumbnails/'.$originalImage);
                    if ($infoImg[0] != $thumbnails) {
                        if (@copy($path.'original/'.$originalImage, $path.'thumbnails/'.$originalImage)) {
                            RCMS_Tools_Tools::resizeImage($path.'thumbnails/'.$originalImage, $thumbnails, 0, true);
                        }
                    }
                } else {
                    if (@copy($path.'original/'.$originalImage, $path.'thumbnails/'.$originalImage)) {
                        RCMS_Tools_Tools::resizeImage($path.'thumbnails/'.$originalImage, $thumbnails, 0, true);
                    }
                }
            }
        }
        //use cooliris
        if ($cooliris) {
            $xmlRssForCooliris = $this->_getXmlRssForCooliris($folder, $originalImages, $useFolder);
            @file_put_contents($path.'/'.$folder.'.xml', $xmlRssForCooliris);
        }

        $this->_generatorView->path = $path;
        $this->_generatorView->useFolder = $useFolder;
        $this->_generatorView->caption = $caption;
        $this->_generatorView->images = $originalImages;
        $this->_generatorView->folder = $folder;
        $this->_generatorView->thumbnails = $thumbnails;
        $this->_generatorView->cooliris = $cooliris;
        $this->_generatorView->coolirisWidth = isset($params['options'][4]) && '' !== $params['options'][4] ? intval(trim($params['options'][4])) : 600;
        $this->_generatorView->coolirisHeight = isset($params['options'][5]) && '' !== $params['options'][5] ? intval(trim($params['options'][5])) : 450;
        $this->_generatorView->coolirisStyle = isset($params['options'][6]) && in_array(trim($params['options'][6]), array('white','black','light','dark')) ? trim($params['options'][6]) : 'white';
        $this->_generatorView->coolirisRows = isset($params['options'][7]) ? intval(trim($params['options'][7])) : 3;
        return $this->_generatorView->render('galleryforfolder.phtml');
    }

    private function _getXmlRssForCooliris($folder, array $images, $useFolder)
    {
		$this->_generatorView->webSiteURL = $this->_siteUrl;
        $this->_generatorView->folder = $folder;
        $this->_generatorView->images = $images;
        $this->_generatorView->useFolder = $useFolder;
        return $this->_generatorView->render('coolirisrssforgallery.phtml');
    }

    public function generateMainMenuImg()
    {
        $categories = $this->_model->getMainMenuCategories();
        if (!is_array($categories)) {
            return '';
        }
        $imgPages = array();
        $tmpPreview = $this->_model->selectAllPathForPages();
        if (is_array($tmpPreview) && count($tmpPreview) > 0) {
            $imgPages = $tmpPreview;
        }
        foreach ($categories as $key => $category) {
            if($category['protected'] == '1' && !$this->_addLinks && !$this->_memberLogged) {
                unset ($categories[$key]);
				continue;
			}
            if (preg_match('/no category/i', trim($category['categoryName']))) {
                unset ($categories[$key]);
                continue;
            }
            if (preg_match('/draft pages/i', trim($category['categoryName']))) {
                unset ($categories[$key]);
                continue;
            }

            $pages = $this->_model->getMainMenuCategoryPages($category['categoryId']);
            if (is_array($pages) && count($pages) > 0) {
                foreach ($pages as $pageKey => $page) {
                    // find preview
                    $pages[$pageKey]['path'] = '';
                    foreach ($imgPages as $img) {
                        if ($img['page_id'] == $page['pageId']) {
                            $pages[$pageKey]['path'] = $img['path'];
                            break;
                        }
                    }
                    if ($page['protected'] == '1' && !$this->_addLinks && !$this->_memberLogged) {
                        unset ($pages[$pageKey]);
                        continue;
                    }
                }
                //sort($pages);
                $categories[$key]['pages'] = $pages;
            } else {
                $categories[$key]['pages'] = array();
            }
        }
        //sort($categories);

        if (count($categories) <= 0) {
            return '';
        }

        $this->_generatorView->categories = $categories;
        $this->_generatorView->classCounter = 0;
        return $this->_generatorView->render('mainmenuimg.phtml');
    }

    public function generateMainMenuFeatured($name)
    {
        $name = trim($name);
        if ($name === '') {
            return '';
        }

        $categories = $this->_model->getMainMenuCategories();
        if (!is_array($categories)) {
            return '';
        }

        $imgPages = array();
        $tmpPreview = $this->_model->selectAllPathForPages();
        if (is_array($tmpPreview) && count($tmpPreview) > 0) {
            $imgPages = $tmpPreview;
        }

        $allFa = array();
        $tmpFa = $this->_model->selectAllFa();
        if (is_array($tmpFa) && count($tmpFa) > 0) {
            $allFa = $tmpFa;
        }

        foreach ($categories as $key => $category) {
            if($category['protected'] == '1' && !$this->_addLinks && !$this->_memberLogged) {
                unset ($categories[$key]);
				continue;
			}
            if (preg_match('/no category/i', trim($category['categoryName']))) {
                unset ($categories[$key]);
                continue;
            }
            if (preg_match('/draft pages/i', trim($category['categoryName']))) {
                unset ($categories[$key]);
                continue;
            }

            $pages = $this->_model->getMainMenuCategoryPages($category['categoryId']);
            if (is_array($pages) && count($pages) > 0) {
                foreach ($pages as $pageKey => $page) {
                    // find preview
                    $pages[$pageKey]['path'] = '';
                    foreach ($imgPages as $img) {
                        if ($img['page_id'] == $page['pageId']) {
                            $pages[$pageKey]['path'] = $img['path'];
                            break;
                        }
                    }
                    // find featured id
                    $pages[$pageKey]['fa'] = false;
                    foreach ($allFa as $fa) {
                        if ($fa['page_id'] == $page['pageId']) {
                            $pages[$pageKey]['fa'] = true;
                            break;
                        }
                    }

                    if ($page['protected'] == '1' && !$this->_addLinks && !$this->_memberLogged) {
                        unset ($pages[$pageKey]);
                        continue;
                    }
                }
                //sort($pages);
                $categories[$key]['pages'] = $pages;
            } else {
                $categories[$key]['pages'] = array();
            }
        }
        //sort($categories);

        if (count($categories) <= 0) {
            return '';
        }

        $this->_generatorView->categories = $categories;
        $this->_generatorView->name = $name;
        $this->_generatorView->counter = 0;
        return $this->_generatorView->render('mainmenufeatured.phtml');
    }

    public function generatePaymentNoticeEmail(array $billingdata, $shipping = null){
        $this->_generatorView->websiteUrl = $this->_siteUrl;
        $this->_generatorView->data = $billingdata;
        if ($shipping) {
            $this->_generatorView->shipping     = true;
            $this->_generatorView->shippingType = $shipping->getShippingType();
            $this->_generatorView->shippingAddress = $shipping->getShippingAddress();
        }
        return $this->_generatorView->render('paymentnoticeemail.phtml');
    }

	public function generateProductCategoriesList() {
		$productCategories = $this->_model->selectProductCategories();
		if(!empty ($productCategories)) {
			$this->_generatorView->websiteUrl = $this->_siteUrl;
			$this->_generatorView->productLandCatUrl = $this->_model->selectLandingUrl(RCMS_Object_Page_Page::P_OPT_PRODCATLANDING);
			$this->_generatorView->productCategories = $productCategories;
			return $this->_generatorView->render('productcategorieslist.phtml');
		}
		return '';
	}

	public function generateProductBrandsList() {
		$productBrands = $this->_model->selectProductBrands();
		if(!empty ($productBrands)) {
			$this->_generatorView->websiteUrl = $this->_siteUrl;
			$this->_generatorView->productLandBrandUrl = $this->_model->selectLandingUrl(RCMS_Object_Page_Page::P_OPT_PRODBRANDLANDING);
			$this->_generatorView->productBrands = $productBrands;
			return $this->_generatorView->render('productbrandslist.phtml');
		}
		return '';
	}

	/**
	 * Generates <ul><li>... list of products, filtered by filter(product category name or brand)
	 *
	 * Replacing {$product_category_landing} / {$product_brand_landing} variable
	 *
	 * @param string $catName
	 * @return string
	 */
	public function generateProductByFilterLanding($filter, $type = '') {
		if(!$filter) {
			return '';
		}
		if($type == 'category') {
			$producsByFilter = $this->_model->selectProductsByCategoryName($filter);
		}
		else {
			$producsByFilter = $this->_model->selectProductsByBrand($filter);
		}
		if(!empty ($producsByFilter)) {
			$this->_generatorView->websiteUrl = $this->_siteUrl;
			$this->_generatorView->productsByFilter = $producsByFilter;
			return $this->_generatorView->render('productbyfilter.phtml');
		}
		return '';
	}

    public function generateRelatedProducts($relatedIds, $withImg = null){
        $this->_generatorView->siteUrl      = $this->_siteUrl;
        $this->_generatorView->relatedIds   = $relatedIds;
        $this->_generatorView->withImg      = $withImg;
        return $this->_generatorView->render('relatedproducts.phtml');
    }

    public function generateInstantQuoteForm($productId){
		$shoppingConfig                       = $this->_model->selectShoppingConfig();
		$this->_generatorView->siteUrl        = $this->_siteUrl;
        $this->_generatorView->productId      = $productId;
        $this->_generatorView->shoppingConfig = ($shoppingConfig) ? $shoppingConfig : array();

		$shipping = new RCMS_Object_Shipping_Shipping();
		if ($shippingAddr = $shipping->getShippingAddress()){
			$location['country']	= $shippingAddr['country'];
            $location['state']		= $shippingAddr['state'];
		} else {
			$location['country']	= $shoppingConfig['country'];
            $location['state']		= $shoppingConfig['state'];
		}
		$this->_generatorView->location = $location;
        return $this->_generatorView->render('quoteformforproduct.phtml');
    }

    private function _generateStarRatingWidget(RCMS_Object_Product_Product $product){
        $this->_generatorView->siteUrl = $this->_siteUrl;
        $this->_generatorView->productId = $product->getId();
        $this->_generatorView->productName = $product->getName();
        $this->_generatorView->productPage = $product->getPageId();
        $page = new RCMS_Object_Page_Page($product->getPageId());
        $this->_generatorView->productPage  = $page->getUrl();
		unset($page);
        $this->_generatorView->rating = $product->getRatingFormatted();
        $this->_generatorView->totalVotes = $product->getTotalVotes() ? $product->getTotalVotes() : '0';

        return $this->_generatorView->render('starratingwidget.phtml');
    }

    /**
     * Generates review form and review list for product template
     * @param RCMS_Object_Product_Product $product
     * @param <boolean> $moderated
     * @return <type>
     */
    private function _generateReviewsList(RCMS_Object_Product_Product $product, $moderated = false){
        $session = new Zend_Session_Namespace($this->_siteUrl);
        $session->moderatedReview = $moderated;
        $this->_generatorView->siteUrl = $this->_siteUrl;
        $this->_generatorView->isLogged = $this->_addLinks;

        $captchaId = RCMS_Tools_Tools::generateCaptcha();
        $limit = 3;
        $this->_generatorView->captchaId    = $captchaId;
        $reviews = $this->_model->selectReviewByProductId($product->getId(),$limit+1,0,$this->_addLinks);
        //$this->_generatorView->productId  = $product->getName();
        if (count($reviews)<=$limit) {
            $this->_generatorView->noMoreLink = true;
        } else {
            $this->_generatorView->noMoreLink = false;
            array_pop($reviews);
        }
        $this->_generatorView->reviews      = $reviews;
        $this->_generatorView->productName  = $product->getName();
        $page = new RCMS_Object_Page_Page($product->getPageId());
        $this->_generatorView->productPage  = $page->getUrl();
        unset($page);
        return $this->_generatorView->render('productreview.phtml');
    }

    /**
     * Generates widget "breadcrumb"
     * @param integer $pageId
     * @return html String with formated bread crumbs
     */
    public function generateBreadcrumbs($pageId){
        //getting session stored data
        $session = new Zend_Session_Namespace($this->_siteUrl);
        if (!isset($session->bc->history) || !isset($session->bc->lastProduct)){
            $session->bc = new stdClass();
			$session->bc->history     = array();
            $session->bc->lastProduct = false;
        }
        $breadcrumb = $session->bc->history;

        $page = $this->_model->selectPageDataForBreadcrumbs($pageId);
        $newCrumb = array('url'=>$page['page_url'],'nav_name'=>$page['page_name']);
        $isProduct = RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName == $page['category_name'];

        $key = array_search($newCrumb, $breadcrumb);
        if ($key++){
            array_splice($breadcrumb, $key);
            unset($page);
        } else {
            if ($session->bc->lastProduct && $isProduct) {
                array_pop($breadcrumb);
            }
            if ($page['show_in_menu'] == '0' || $isProduct ){
                $breadcrumb[] = $newCrumb;
            } else {
                $breadcrumb = array();

                if ($page['category_id']>0){
                    $breadcrumb[] = array(
                                'url' => $page['category_url'],
                                'nav_name' => $page['category_name']
                                );
                }
                if ($page['page_url']!='index'){
                    $breadcrumb[] = $newCrumb;
                }
            }

        }
        //saving breadcrumbs to session
        $session->bc->history = $breadcrumb;
        $session->bc->lastProduct = $isProduct;

        //generating html widget for page
        $html = array('<a href="'.$this->_siteUrl.'">Home</a>');
        $lastElem = array_pop($breadcrumb);
        foreach ($breadcrumb as $elem){
            if($elem['url'] !='index'){
                $html[] = '<a href="'.$this->_siteUrl.$elem['url'].'.html">'.$elem['nav_name'].'</a>';
            }
        }
        if (!empty($lastElem)) $html[] = '<span>'.$lastElem['nav_name'].'</span>';
        $html = '<div id="breadcrumbs">'.implode($html,' >> ').'</div>';
        return $html;
    }

    private function _generateAddToCartWidget($productId, $showAmountField = false){
        $html = '<form action="javascript:;">';
        if ($showAmountField) $html .= '<input type="number" id="add-amount-'.$productId.'" class="addtocart-amount" min="1" value="1" />';
        $html .= '<input type="button" class="addtocart" value="{%Add to Cart%}" onclick="addToCart(\''.$productId.'\');" /></form>';
        return $html;
    }

    private function _generateFreebiesWidget($freebiesList, $onSaleUntilDate = null) {
		if (!empty ($freebiesList))
		{
			$html  = '<div class="freebies">';
			$html .= '<h5>{%Offered in addition%}:</h5>';
			if (is_string($freebiesList)){
				$freebiesList = explode(',', $freebiesList);
			}
			if (is_array($freebiesList) && !empty($freebiesList)){
				$html .=  '<ul>';
				foreach ($freebiesList as $freebieId) {
					$freebie = new RCMS_Object_Product_Product($freebieId);
					$html .= '<li>';
					$html .= '<img src="'.$this->_siteUrl.$freebie->getPhoto().'" alt="'.$freebie->getName().'" />';
					$html .= '<span>'.$freebie->getName().'</span>';
					$html .= '</li>';
					unset ($freebie);
				}
				$html .=  '</ul>';
			}
			if ($onSaleUntilDate) {
				$html .= '<p>{%Offer valid until%}: '.date('Y-m-d', strtotime($onSaleUntilDate)).'</p>';
			}
			$html .= '</div><!--freebies list-->';
			return $html;
		}
		return '';
	}
}
